import consul
from configurate import CONSUL


class Consul(object):

    def __init__(self):
        self._host = CONSUL.get("host")
        self._port = CONSUL.get("port")
        """
            初始化，连接consul服务器
        """
        self._consul = consul.Consul(self._host, self._port)

    def register_service(self, name, service_id, host, port, tags=None):
        tags = tags or []
        # 注册服务
        self._consul.agent.service.register(
            name,
            service_id,
            host,
            port,
            tags,
            # 健康检查ip端口，检查时间：5,超时时间：30，注销时间：30s
            check=consul.Check().tcp(host, port, "60s"))

    def get_service_by_id(self, id):
        services = self._consul.agent.services()
        service = services.get(id)
        if not service:
            return None, None
        addr = "{0}:{1}".format(service['Address'], service['Port'])
        return service, addr

    def get_service_all(self):
        results = []
        services = self._consul.agent.services()
        for service in services:
            bean = services.get(service)
            addr = "{0}:{1}".format(bean['Address'], bean['Port'])
            results.append((bean, addr))
        return results
# if __name__ == '__main__':
# host = "47.103.91.162"
# consul_client = Consul()

# name = "warehouseInventory"
# host = "127.0.0.1"
# port = 8500
# consul_client.register_service(name, host, port)

# check = consul.Check().tcp(host, port, "5s")
# print(check)
# res = consul_client.get_service_all()
# print(res)
# res1 = consul_client.get_service_by_id("TransactionManager-192-168-56-1-7970")
# print(res1)
